package xyz.lwm.lazycat.netpipe.util;

import xyz.lwm.lazycat.netpipe.domain.vo.Token;
import xyz.lwm.lazycat.netpipe.domain.enums.TokenType;
import xyz.lwm.lazycat.utility.It;
import xyz.lwm.lazycat.utility.cache.Cache;
import xyz.lwm.lazycat.utility.cache.CaffeineCaches;

import java.time.Duration;
import java.util.UUID;

/**
 * 令牌工具类
 *
 * @author lwm
 */
public abstract class Tokens {

    // key: token.string; value: userId
    private static final Cache<String, String> TOKENS = CaffeineCaches.getCache("Tokens",
            caffeine -> caffeine.maximumSize(10000).expireAfterAccess(Duration.ofHours(12)));

    /**
     * 创建令牌
     *
     * @param type  令牌类型
     * @param userId 用户ID
     * @return 令牌
     */
    public static Token create(TokenType type, String userId) {
        Token token = new Token().setType(type).setKey(UUID.randomUUID().toString());
        TOKENS.set(token.toString(), userId);
        return token;
    }

    /**
     * 验证令牌是否有效
     *
     * @param token 令牌
     * @return 是否有效
     */
    public static boolean isValid(String token) {
        return getUserId(token) != null;
    }

    /**
     * 获取用户ID
     *
     * @param token 令牌
     * @return 用户ID
     */
    public static String getUserId(String token) {
        return It.of(Token.of(token)).let(Tokens::getUserId).getOr(null);
    }

    /**
     * 获取用户ID
     *
     * @param token 令牌
     * @return 用户ID
     */
    public static String getUserId(Token token) {
        return TOKENS.getIfPresent(token.toString());
    }

}
